[[...path]].page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import React, { useEffect } from 'react';
  2. import { isClient, pagePathUtils, pathUtils } from '@growi/core';
  3. import ExtensibleCustomError from 'extensible-custom-error';
  4. import { isValidObjectId } from 'mongoose';
  5. import {
  6. NextPage, GetServerSideProps, GetServerSidePropsContext,
  7. } from 'next';
  8. import dynamic from 'next/dynamic';
  9. import Head from 'next/head';
  10. import { useRouter } from 'next/router';
  11. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  12. // import { PageComments } from '~/components/PageComment/PageComments';
  13. // import { useTranslation } from '~/i18n';
  14. import { isPopulated } from '~/interfaces/common';
  15. import { CrowiRequest } from '~/interfaces/crowi-request';
  16. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  17. // import { useIndentSize } from '~/stores/editor';
  18. // import { useRendererSettings } from '~/stores/renderer';
  19. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  20. import { IPageWithMeta } from '~/interfaces/page';
  21. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  22. import { PageModel, PageDocument } from '~/server/models/page';
  23. import { serializeUserSecurely } from '~/server/models/serializers/user-serializer';
  24. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  25. import Xss from '~/services/xss';
  26. import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
  27. import {
  28. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  29. } from '~/stores/ui';
  30. import loggerFactory from '~/utils/logger';
  31. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  32. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  33. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  34. import { BasicLayout } from '../components/BasicLayout';
  35. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  36. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  37. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  38. import {
  39. useCurrentUser, useCurrentPagePath,
  40. useOwnerOfCurrentPage, useIsLatestRevision,
  41. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  42. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  43. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  44. useAclEnabled, useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax,
  45. useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured,
  46. } from '../stores/context';
  47. import { useXss } from '../stores/xss';
  48. import { CommonProps, getServerSideCommonProps, useCustomTitle } from './commons';
  49. // import { useCurrentPageSWR } from '../stores/page';
  50. const logger = loggerFactory('growi:pages:all');
  51. const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  52. const { removeHeadingSlash } = pathUtils;
  53. const IdenticalPathPage = (): JSX.Element => {
  54. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  55. return <IdenticalPathPage />;
  56. };
  57. type Props = CommonProps & {
  58. currentUser: string,
  59. pageWithMetaStr: string,
  60. // pageUser?: any,
  61. // redirectTo?: string;
  62. // redirectFrom?: string;
  63. // shareLinkId?: string;
  64. isLatestRevision: boolean
  65. isIdenticalPathPage?: boolean,
  66. isForbidden: boolean,
  67. isNotFound: boolean,
  68. // isAbleToDeleteCompletely: boolean,
  69. isSearchServiceConfigured: boolean,
  70. isSearchServiceReachable: boolean,
  71. isSearchScopeChildrenAsDefault: boolean,
  72. isSlackConfigured: boolean,
  73. // isMailerSetup: boolean,
  74. isAclEnabled: boolean,
  75. // hasSlackConfig: boolean,
  76. // drawioUri: string,
  77. // hackmdUri: string,
  78. // mathJax: string,
  79. // noCdn: string,
  80. // highlightJsStyle: string,
  81. // isAllReplyShown: boolean,
  82. // isContainerFluid: boolean,
  83. // editorConfig: any,
  84. isEnabledStaleNotification: boolean,
  85. // isEnabledLinebreaks: boolean,
  86. // isEnabledLinebreaksInComments: boolean,
  87. // adminPreferredIndentSize: number,
  88. // isIndentSizeForced: boolean,
  89. // UI
  90. userUISettings: UserUISettingsDocument | null
  91. // Sidebar
  92. sidebarConfig: ISidebarConfig,
  93. };
  94. const GrowiPage: NextPage<Props> = (props: Props) => {
  95. // const { t } = useTranslation();
  96. const router = useRouter();
  97. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  98. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  99. // commons
  100. useAppTitle(props.appTitle);
  101. useSiteUrl(props.siteUrl);
  102. useXss(new Xss());
  103. // useEditorConfig(props.editorConfig);
  104. useConfidential(props.confidential);
  105. useCsrfToken(props.csrfToken);
  106. // UserUISettings
  107. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  108. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  109. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  110. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  111. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  112. // page
  113. useCurrentPagePath(props.currentPathname);
  114. useIsLatestRevision(props.isLatestRevision);
  115. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  116. useIsForbidden(props.isForbidden);
  117. useIsNotFound(props.isNotFound);
  118. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  119. // useShared();
  120. // useShareLinkId(props.shareLinkId);
  121. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  122. useIsSharedUser(false); // this page cann't be routed for '/share'
  123. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  124. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  125. useIsSearchServiceReachable(props.isSearchServiceReachable);
  126. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  127. useIsSlackConfigured(props.isSlackConfigured);
  128. // useIsMailerSetup(props.isMailerSetup);
  129. useIsAclEnabled(props.isAclEnabled);
  130. // useHasSlackConfig(props.hasSlackConfig);
  131. // useDrawioUri(props.drawioUri);
  132. // useHackmdUri(props.hackmdUri);
  133. // useMathJax(props.mathJax);
  134. // useNoCdn(props.noCdn);
  135. // useIndentSize(props.adminPreferredIndentSize);
  136. // useRendererSettings({
  137. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  138. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  139. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  140. // isIndentSizeForced: props.isIndentSizeForced,
  141. // });
  142. // const { data: editorMode } = useEditorMode();
  143. let pageWithMeta: IPageWithMeta | undefined;
  144. if (props.pageWithMetaStr != null) {
  145. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  146. }
  147. useCurrentPageId(pageWithMeta?.data._id);
  148. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  149. // useSWRxPage(pageWithMeta?.data._id);
  150. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  151. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  152. useCurrentPagePath(pageWithMeta?.data.path);
  153. useCurrentPathname(props.currentPathname);
  154. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  155. useEffect(() => {
  156. if (isClient() && window.location.pathname !== props.currentPathname) {
  157. router.replace(props.currentPathname, undefined, { shallow: true });
  158. }
  159. }, [props.currentPathname, router]);
  160. const classNames: string[] = [];
  161. // switch (editorMode) {
  162. // case EditorMode.Editor:
  163. // classNames.push('on-edit', 'builtin-editor');
  164. // break;
  165. // case EditorMode.HackMD:
  166. // classNames.push('on-edit', 'hackmd');
  167. // break;
  168. // }
  169. // if (props.isContainerFluid) {
  170. // classNames.push('growi-layout-fluid');
  171. // }
  172. // if (page == null) {
  173. // classNames.push('not-found-page');
  174. // }
  175. return (
  176. <>
  177. <Head>
  178. {/*
  179. {renderScriptTagByName('drawio-viewer')}
  180. {renderScriptTagByName('mathjax')}
  181. {renderScriptTagByName('highlight-addons')}
  182. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  183. */}
  184. </Head>
  185. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  186. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  187. <header className="py-0">
  188. {/* <GrowiSubNavigation /> */}
  189. GrowiSubNavigation
  190. </header>
  191. <div className="d-edit-none">
  192. {/* <GrowiSubNavigationSwitcher /> */}
  193. GrowiSubNavigationSwitcher
  194. </div>
  195. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  196. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  197. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  198. <div className="row">
  199. <div className="col">
  200. <div id="content-main" className="content-main grw-container-convertible">
  201. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  202. { !props.isIdenticalPathPage && (
  203. <>
  204. <PageAlerts />
  205. { props.isForbidden
  206. ? <>ForbiddenPage</>
  207. : <DisplaySwitcher />
  208. }
  209. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  210. {/* <PageStatusAlert /> */}
  211. PageStatusAlert
  212. </>
  213. ) }
  214. </div>
  215. </div>
  216. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  217. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  218. <div id="revision-toc-content" className="revision-toc-content"></div>
  219. </div>
  220. </div> */}
  221. </div>
  222. </div>
  223. <footer>
  224. {/* <PageComments /> */}
  225. PageComments
  226. </footer>
  227. <UnsavedAlertDialog />
  228. </BasicLayout>
  229. </>
  230. );
  231. };
  232. function getPageIdFromPathname(currentPathname: string): string | null {
  233. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  234. }
  235. class MultiplePagesHitsError extends ExtensibleCustomError {
  236. pagePath: string;
  237. constructor(pagePath: string) {
  238. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  239. this.pagePath = pagePath;
  240. }
  241. }
  242. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
  243. const req: CrowiRequest = context.req as CrowiRequest;
  244. const { crowi } = req;
  245. const { revisionId } = req.query;
  246. const Page = crowi.model('Page') as PageModel;
  247. const { pageService } = crowi;
  248. const { currentPathname } = props;
  249. const pageId = getPageIdFromPathname(currentPathname);
  250. const isPermalink = _isPermalink(currentPathname);
  251. const { user } = req;
  252. // check whether the specified page path hits to multiple pages
  253. if (!isPermalink) {
  254. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  255. if (count > 1) {
  256. throw new MultiplePagesHitsError(currentPathname);
  257. }
  258. }
  259. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  260. const page = result?.data as unknown as PageDocument;
  261. // populate
  262. if (page != null) {
  263. page.initLatestRevisionField(revisionId);
  264. await page.populateDataToShowRevision();
  265. }
  266. return result;
  267. }
  268. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
  269. const req: CrowiRequest = context.req as CrowiRequest;
  270. const { crowi } = req;
  271. const Page = crowi.model('Page') as PageModel;
  272. const { currentPathname } = props;
  273. const pageId = getPageIdFromPathname(currentPathname);
  274. const isPermalink = _isPermalink(currentPathname);
  275. const page = pageWithMeta?.data;
  276. if (props.isIdenticalPathPage) {
  277. // TBD
  278. }
  279. else if (page == null) {
  280. props.isNotFound = true;
  281. // check the page is forbidden or just does not exist.
  282. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  283. props.isForbidden = count > 0;
  284. }
  285. else {
  286. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  287. if (isPermalink && page.isEmpty) {
  288. props.currentPathname = page.path;
  289. }
  290. // /path/to/page ==> /62a88db47fed8b2d94f30000
  291. if (!isPermalink && !page.isEmpty) {
  292. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  293. if (!isToppage) {
  294. props.currentPathname = `/${page._id}`;
  295. }
  296. }
  297. }
  298. }
  299. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  300. // const req: CrowiRequest = context.req as CrowiRequest;
  301. // const { crowi } = req;
  302. // const UserModel = crowi.model('User');
  303. // if (isUserPage(props.currentPagePath)) {
  304. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  305. // if (user != null) {
  306. // props.pageUser = JSON.stringify(user.toObject());
  307. // }
  308. // }
  309. // }
  310. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  311. const req: CrowiRequest = context.req as CrowiRequest;
  312. const { crowi } = req;
  313. const {
  314. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  315. } = crowi;
  316. props.isSearchServiceConfigured = searchService.isConfigured;
  317. props.isSearchServiceReachable = searchService.isReachable;
  318. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  319. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  320. // props.isMailerSetup = mailService.isMailerSetup;
  321. props.isAclEnabled = aclService.isAclEnabled();
  322. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  323. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  324. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  325. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  326. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  327. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  328. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  329. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  330. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  331. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  332. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  333. // props.editorConfig = {
  334. // upload: {
  335. // image: crowi.fileUploadService.getIsUploadable(),
  336. // file: crowi.fileUploadService.getFileUploadEnabled(),
  337. // },
  338. // };
  339. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  340. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  341. props.sidebarConfig = {
  342. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  343. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  344. };
  345. }
  346. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  347. const req: CrowiRequest = context.req as CrowiRequest;
  348. const { crowi, user } = req;
  349. const { revisionId } = req.query;
  350. const Revision = crowi.model('Revision');
  351. const result = await getServerSideCommonProps(context);
  352. // check for presence
  353. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  354. if (!('props' in result)) {
  355. throw new Error('invalid getSSP result');
  356. }
  357. const props: Props = result.props as Props;
  358. let pageWithMeta;
  359. try {
  360. pageWithMeta = await getPageData(context, props);
  361. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  362. }
  363. catch (err) {
  364. if (err instanceof MultiplePagesHitsError) {
  365. props.isIdenticalPathPage = true;
  366. }
  367. else {
  368. throw err;
  369. }
  370. }
  371. // check revision
  372. const isSpecifiedRevisionExist = isValidObjectId(revisionId) ? await Revision.exists({ _id: revisionId }) : false;
  373. const page = pageWithMeta?.data;
  374. if (page == null || page.latestRevision == null || revisionId == null || !isSpecifiedRevisionExist) {
  375. props.isLatestRevision = true;
  376. }
  377. else {
  378. props.isLatestRevision = page.latestRevision.toString() === revisionId;
  379. }
  380. injectRoutingInformation(context, props, pageWithMeta);
  381. injectServerConfigurations(context, props);
  382. if (user != null) {
  383. props.currentUser = JSON.stringify(user);
  384. }
  385. // UI
  386. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  387. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  388. return {
  389. props,
  390. };
  391. };
  392. export default GrowiPage;